﻿using BLL;
using JLHelper;
using Microsoft.AspNetCore.Mvc;
using NetHelperCore;
using System.Diagnostics;

namespace ServiceManage.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class ServiceController : ControllerBase
    {

        /// <summary>
        /// 获取需要管理的服务列表
        /// </summary>
        /// <returns></returns>
        public ServiceResultModel ServiceListGet()
        {
            ServiceResultModel _rm = new ServiceResultModel()
            {
                Success = -1,
                Result = null,
                ErrorMessage = ""
            };

            try
            {
                _rm.Success = 1;
                if (ConfigBLL.ServiceInfoList == null || ConfigBLL.ServiceInfoList.Count == 0)
                {
                    _rm.Result = null;

                }
                else
                {
                    List<object> _serviceList = new List<object>();
                    foreach (ServiceInfo _service in ConfigBLL.ServiceInfoList)
                    {
                        bool _isInstall = WindowsServiceHelper.IsServiceIsExisted(_service.ServiceName);
                        bool _isRun = false;
                        if (_isInstall)
                        {
                            _isRun = WindowsServiceHelper.IsServiceStart(_service.ServiceName);
                        }
                        _serviceList.Add(new
                        {
                            ID = _service.ID,
                            ServiceName = _service.ServiceName,
                            ServiceDescription = _service.ServiceDescription,
                            FilePath = _service.FilePath,
                            Port = _service.Port,
                            IsInstall = _isInstall,
                            IsRun = _isRun,
                        });
                    }
                    _rm.Result = _serviceList;
                }

            }
            catch (Exception ex)
            {
                string _errorID = Convert.ToString(NetHelperCore.CommonHelper.GetNewID(1));
                LogHelper.WriteLog(LogHelper.LogType.Error, _errorID + "---" + ex.Message + "\r\n" + ex.StackTrace, "", new StackTrace(new StackFrame(true)).GetFrame(0).GetMethod().Name);
                _rm.Success = 0;
                _rm.ErrorMessage = "错误代码:" + _errorID;
            }


            return _rm;
        }

        /// <summary>
        /// 添加需要管理的服务
        /// </summary>
        /// <returns></returns>
        public ServiceResultModel ServiceAdd()
        {
            ServiceResultModel _result = new ServiceResultModel()
            {
                Success = -1,
                Result = null,
                ErrorMessage = ""
            };

            try
            {
                string _param = Request.Form["ParamStr"].ToString();
                if (!string.IsNullOrWhiteSpace(_param))
                {
                    JsonHelper _json = new JsonHelper(_param);
                    string _filePath = _json.GetVar("FilePath");
                    string _serviceName = _json.GetVar("ServiceName");
                    string _serviceDescription = _json.GetVar("ServiceDescription");
                    int _port = Convert.ToInt32(_json.GetVar("Port"));
                    if (string.IsNullOrWhiteSpace(_filePath))
                    {
                        _result.Success = 0;
                        _result.ErrorMessage = "程序路径不可为空";
                        return _result;
                    }
                    if (ConfigBLL.ServiceInfoList == null)
                    {
                        ConfigBLL.ServiceInfoList = new List<ServiceInfo>();
                    }
                    ConfigBLL.ServiceInfoList.Add(new ServiceInfo()
                    {
                        ID = NetHelperCore.CommonHelper.GetNewID(1),
                        ServiceName = _serviceName,
                        ServiceDescription = _serviceDescription,
                        FilePath = _filePath,
                        Port = _port
                    });
                    ConfigBLL.SaveConfig();
                }

                _result.Success = 1;
                _result.Result = ConfigBLL.ServiceInfoList;
            }
            catch (Exception ex)
            {
                string _errorID = Convert.ToString(NetHelperCore.CommonHelper.GetNewID(1));
                LogHelper.WriteLog(LogHelper.LogType.Error, _errorID + "---" + ex.Message + "\r\n" + ex.StackTrace, "", new StackTrace(new StackFrame(true)).GetFrame(0).GetMethod().Name);
                _result.Success = 0;
                _result.ErrorMessage = "错误代码:" + _errorID;

            }


            return _result;
        }

        /// <summary>
        /// 更新需要管理的服务
        /// </summary>
        /// <returns></returns>
        public ServiceResultModel ServiceUpdate()
        {
            ServiceResultModel _rm = new ServiceResultModel()
            {
                Success = -1,
                Result = null,
                ErrorMessage = ""
            };

            try
            {
                string _param = Request.Form["ParamStr"].ToString();
                if (!string.IsNullOrWhiteSpace(_param))
                {
                    JsonHelper _json = new JsonHelper(_param);
                    long _id = Convert.ToInt64(_json.GetVar("ID"));
                    string _filePath = _json.GetVar("FilePath");
                    int _port = Convert.ToInt32(_json.GetVar("Port"));

                    if (_id == 0)
                    {
                        _rm.Success = -2;
                        _rm.ErrorMessage = "未找到配置的程序信息";
                        return _rm;
                    }
                    if (string.IsNullOrWhiteSpace(_filePath))
                    {
                        _rm.Success = 0;
                        _rm.ErrorMessage = "程序路径不可为空";
                        return _rm;
                    }
                    ServiceInfo _serviceInfo = ConfigBLL.ServiceInfoList.Find(it => it.ID == _id);
                    if (_serviceInfo == null)
                    {
                        _rm.Success = -2;
                        _rm.ErrorMessage = "未找到配置的程序信息";
                        return _rm;
                    }
                    else
                    {
                        _serviceInfo.FilePath = _filePath;
                        _serviceInfo.Port = _port;
                        ConfigBLL.SaveConfig();
                        _rm.Success = 1;
                    }
                }
            }
            catch (Exception ex)
            {
                string _errorID = Convert.ToString(NetHelperCore.CommonHelper.GetNewID(1));
                LogHelper.WriteLog(LogHelper.LogType.Error, _errorID + "---" + ex.Message + "\r\n" + ex.StackTrace, "", new StackTrace(new StackFrame(true)).GetFrame(0).GetMethod().Name);
                _rm.Success = 0;
                _rm.ErrorMessage = "错误代码:" + _errorID;
            }


            return _rm;
        }

        /// <summary>
        /// 删除需要管理的服务
        /// </summary>
        /// <returns></returns>
        public ServiceResultModel ServiceDelete()
        {
            ServiceResultModel _rm = new ServiceResultModel()
            {
                Success = -1,
                Result = null,
                ErrorMessage = ""
            };

            try
            {
                string _param = Request.Form["ParamStr"].ToString();
                if (!string.IsNullOrWhiteSpace(_param))
                {
                    JsonHelper _json = new JsonHelper(_param);
                    long _id = Convert.ToInt64(_json.GetVar("ID"));
                    string _filePath = _json.GetVar("FilePath");
                    int _port = Convert.ToInt32(_json.GetVar("Port"));

                    if (_id == 0)
                    {
                        _rm.Success = -2;
                        _rm.ErrorMessage = "未找到配置的程序信息";
                        return _rm;
                    }
                    ServiceInfo _serviceInfo = ConfigBLL.ServiceInfoList.Find(it => it.ID == _id);
                    if (_serviceInfo == null)
                    {
                        _rm.Success = -2;
                        _rm.ErrorMessage = "未找到配置的程序信息";
                        return _rm;
                    }
                    else
                    {
                        ConfigBLL.ServiceInfoList.Remove(_serviceInfo);
                        ConfigBLL.SaveConfig();
                        _rm.Success = 1;
                    }

                }
            }
            catch (Exception ex)
            {
                string _errorID = Convert.ToString(NetHelperCore.CommonHelper.GetNewID(1));
                LogHelper.WriteLog(LogHelper.LogType.Error, _errorID + "---" + ex.Message + "\r\n" + ex.StackTrace, "", new StackTrace(new StackFrame(true)).GetFrame(0).GetMethod().Name);
                _rm.Success = 0;
                _rm.ErrorMessage = "错误代码:" + _errorID;
            }


            return _rm;
        }

        /// <summary>
        /// 安装服务
        /// </summary>
        /// <returns></returns>
        public ServiceResultModel ServiceInstall()
        {
            ServiceResultModel _rm = new ServiceResultModel()
            {
                Success = -1,
                Result = null,
                ErrorMessage = ""
            };

            try
            {
                string _param = Request.Form["ParamStr"].ToString();
                if (!string.IsNullOrWhiteSpace(_param))
                {
                    JsonHelper _json = new JsonHelper(_param);
                    long _id = Convert.ToInt64(_json.GetVar("ID"));

                    if (_id == 0)
                    {
                        _rm.Success = -2;
                        _rm.ErrorMessage = "未找到配置的程序信息";
                        return _rm;
                    }

                    ServiceInfo _serviceInfo = ConfigBLL.ServiceInfoList.Find(it => it.ID == _id);
                    if (_serviceInfo == null)
                    {
                        _rm.Success = -2;
                        _rm.ErrorMessage = "未找到配置的程序信息";
                        return _rm;
                    }
                    else
                    {
                        if (WindowsServiceHelper.IsServiceIsExisted(_serviceInfo.ServiceName))
                        {
                            _rm.Success = 0;
                            _rm.ErrorMessage = "服务已安装，无需重复安装!";
                            return _rm;
                        }

                        using (Process p = new Process())
                        {
                            p.StartInfo.FileName = NetHelperCore.FileHelper.GetRunPath() + @"\Lib\WindowsService.exe";//可执行程序路径
                            p.StartInfo.Arguments = "Type=ServiceInstall ServiceName=" + _serviceInfo.ServiceName + " ServicePath=" + _serviceInfo.FilePath + " KillProcessID=" + Convert.ToString(0) + " ServiceDescription=" + _serviceInfo.ServiceDescription;//参数以空格分隔，如果某个参数为空，可以传入""
                            p.StartInfo.UseShellExecute = true;//是否使用操作系统shell启动
                            p.StartInfo.CreateNoWindow = true;//不显示程序窗口
                            p.StartInfo.Verb = "runas";
                            p.Start();
                            p.WaitForExit();
                            //正常运行结束放回代码为0
                            if (p.ExitCode == 0)
                            {
                                _rm.Success = 1;
                                _rm.Result = true;

                            }
                        }
                        _rm.Success = 1;

                    }


                }
            }
            catch (Exception ex)
            {
                string _errorID = Convert.ToString(NetHelperCore.CommonHelper.GetNewID(1));
                LogHelper.WriteLog(LogHelper.LogType.Error, _errorID + "---" + ex.Message + "\r\n" + ex.StackTrace, "", new StackTrace(new StackFrame(true)).GetFrame(0).GetMethod().Name);
                _rm.Success = 0;
                _rm.ErrorMessage = "错误代码:" + _errorID;
            }


            return _rm;
        }

        /// <summary>
        /// 卸载服务
        /// </summary>
        /// <returns></returns>
        public ServiceResultModel ServiceUnInstall()
        {
            ServiceResultModel _rm = new ServiceResultModel()
            {
                Success = -1,
                Result = null,
                ErrorMessage = ""
            };

            try
            {
                string _param = Request.Form["ParamStr"].ToString();
                if (!string.IsNullOrWhiteSpace(_param))
                {
                    JsonHelper _json = new JsonHelper(_param);
                    long _id = Convert.ToInt64(_json.GetVar("ID"));

                    if (_id == 0)
                    {
                        _rm.Success = -2;
                        _rm.ErrorMessage = "未找到配置的程序信息";
                        return _rm;
                    }

                    ServiceInfo _serviceInfo = ConfigBLL.ServiceInfoList.Find(it => it.ID == _id);
                    if (_serviceInfo == null)
                    {
                        _rm.Success = -2;
                        _rm.ErrorMessage = "未找到配置的程序信息";
                        return _rm;
                    }
                    else
                    {
                        if (!WindowsServiceHelper.IsServiceIsExisted(_serviceInfo.ServiceName))
                        {
                            _rm.Success = 0;
                            _rm.ErrorMessage = "服务已卸载!";
                            return _rm;
                        }

                        using (Process p = new Process())
                        {
                            p.StartInfo.FileName = NetHelperCore.FileHelper.GetRunPath() + @"\Lib\WindowsService.exe";//可执行程序路径
                            p.StartInfo.Arguments = "Type=ServiceUnInstall ServiceName=" + _serviceInfo.ServiceName;//参数以空格分隔，如果某个参数为空，可以传入""
                            p.StartInfo.UseShellExecute = true;//是否使用操作系统shell启动
                            p.StartInfo.CreateNoWindow = true;//不显示程序窗口
                            p.StartInfo.Verb = "runas";
                            p.Start();
                            p.WaitForExit();
                            //正常运行结束放回代码为0
                            if (p.ExitCode == 0)
                            {
                                _rm.Success = 1;
                                _rm.Result = true;
                            }
                        }

                        _rm.Success = 1;

                    }


                }
            }
            catch (Exception ex)
            {
                string _errorID = Convert.ToString(NetHelperCore.CommonHelper.GetNewID(1));
                LogHelper.WriteLog(LogHelper.LogType.Error, _errorID + "---" + ex.Message + "\r\n" + ex.StackTrace, "", new StackTrace(new StackFrame(true)).GetFrame(0).GetMethod().Name);
                _rm.Success = 0;
                _rm.ErrorMessage = "错误代码:" + _errorID;
            }


            return _rm;
        }

        /// <summary>
        /// 启动服务
        /// </summary>
        /// <returns></returns>
        public ServiceResultModel ServiceStart()
        {
            ServiceResultModel _rm = new ServiceResultModel()
            {
                Success = -1,
                Result = null,
                ErrorMessage = ""
            };

            try
            {
                string _param = Request.Form["ParamStr"].ToString();
                if (!string.IsNullOrWhiteSpace(_param))
                {
                    JsonHelper _json = new JsonHelper(_param);
                    long _id = Convert.ToInt64(_json.GetVar("ID"));

                    if (_id == 0)
                    {
                        _rm.Success = -2;
                        _rm.ErrorMessage = "未找到配置的程序信息";
                        return _rm;
                    }

                    ServiceInfo _serviceInfo = ConfigBLL.ServiceInfoList.Find(it => it.ID == _id);
                    if (_serviceInfo == null)
                    {
                        _rm.Success = -2;
                        _rm.ErrorMessage = "未找到配置的程序信息";
                        return _rm;
                    }
                    else
                    {
                        if (!WindowsServiceHelper.IsServiceIsExisted(_serviceInfo.ServiceName))
                        {
                            _rm.Success = 0;
                            _rm.ErrorMessage = "服务未安装!";
                            return _rm;
                        }

                        if (WindowsServiceHelper.IsServiceStart(_serviceInfo.ServiceName))
                        {
                            _rm.Success = 0;
                            _rm.ErrorMessage = "服务已启动!";
                            return _rm;
                        }

                        using (Process p = new Process())
                        {
                            p.StartInfo.FileName = NetHelperCore.FileHelper.GetRunPath() + @"\Lib\WindowsService.exe";//可执行程序路径
                            p.StartInfo.Arguments = "Type=ServiceStart ServiceName=" + _serviceInfo.ServiceName;//参数以空格分隔，如果某个参数为空，可以传入""
                            p.StartInfo.UseShellExecute = true;//是否使用操作系统shell启动
                            p.StartInfo.CreateNoWindow = true;//不显示程序窗口
                            p.StartInfo.Verb = "runas";
                            p.Start();
                            p.WaitForExit();
                            //正常运行结束放回代码为0
                            if (p.ExitCode == 0)
                            {
                                _rm.Success = 1;
                                _rm.Result = true;
                            }
                        }

                    }
                }
            }
            catch (Exception ex)
            {
                string _errorID = Convert.ToString(NetHelperCore.CommonHelper.GetNewID(1));
                LogHelper.WriteLog(LogHelper.LogType.Error, _errorID + "---" + ex.Message + "\r\n" + ex.StackTrace, "", new StackTrace(new StackFrame(true)).GetFrame(0).GetMethod().Name);
                _rm.Success = 0;
                _rm.ErrorMessage = "错误代码:" + _errorID;
            }


            return _rm;
        }

        /// <summary>
        /// 停止服务
        /// </summary>
        /// <returns></returns>
        public ServiceResultModel ServiceStop()
        {
            ServiceResultModel _rm = new ServiceResultModel()
            {
                Success = -1,
                Result = null,
                ErrorMessage = ""
            };

            try
            {
                string _param = Request.Form["ParamStr"].ToString();
                if (!string.IsNullOrWhiteSpace(_param))
                {
                    JsonHelper _json = new JsonHelper(_param);
                    long _id = Convert.ToInt64(_json.GetVar("ID"));

                    if (_id == 0)
                    {
                        _rm.Success = -2;
                        _rm.ErrorMessage = "未找到配置的程序信息";
                        return _rm;
                    }

                    ServiceInfo _serviceInfo = ConfigBLL.ServiceInfoList.Find(it => it.ID == _id);
                    if (_serviceInfo == null)
                    {
                        _rm.Success = -2;
                        _rm.ErrorMessage = "未找到配置的程序信息";
                        return _rm;
                    }
                    else
                    {
                        if (!WindowsServiceHelper.IsServiceIsExisted(_serviceInfo.ServiceName))
                        {
                            _rm.Success = 0;
                            _rm.ErrorMessage = "服务未安装!";
                            return _rm;
                        }

                        if (!WindowsServiceHelper.IsServiceStart(_serviceInfo.ServiceName))
                        {
                            _rm.Success = 0;
                            _rm.ErrorMessage = "服务未启动!";
                            return _rm;
                        }

                        using (Process p = new Process())
                        {
                            p.StartInfo.FileName = NetHelperCore.FileHelper.GetRunPath() + @"\Lib\WindowsService.exe";//可执行程序路径
                            p.StartInfo.Arguments = "Type=ServiceStop ServiceName=" + _serviceInfo.ServiceName;//参数以空格分隔，如果某个参数为空，可以传入""
                            p.StartInfo.UseShellExecute = true;//是否使用操作系统shell启动
                            p.StartInfo.CreateNoWindow = true;//不显示程序窗口
                            p.StartInfo.Verb = "runas";
                            p.Start();
                            p.WaitForExit();
                            //正常运行结束放回代码为0
                            if (p.ExitCode == 0)
                            {
                                _rm.Success = 1;
                                _rm.Result = true;
                            }
                        }
                        _rm.Success = 1;

                    }
                }
            }
            catch (Exception ex)
            {
                string _errorID = Convert.ToString(NetHelperCore.CommonHelper.GetNewID(1));
                LogHelper.WriteLog(LogHelper.LogType.Error, _errorID + "---" + ex.Message + "\r\n" + ex.StackTrace, "", new StackTrace(new StackFrame(true)).GetFrame(0).GetMethod().Name);
                _rm.Success = 0;
                _rm.ErrorMessage = "错误代码:" + _errorID;
            }


            return _rm;
        }

        /// <summary>
        /// 使用SVN更新服务文件
        /// </summary>
        /// <returns></returns>
        public ServiceResultModel ServiceSVNUpdate()
        {
            ServiceResultModel _rm = new ServiceResultModel()
            {
                Success = -1,
                Result = null,
                ErrorMessage = ""
            };

            try
            {
                string _param = Request.Form["ParamStr"].ToString();
                if (!string.IsNullOrWhiteSpace(_param))
                {
                    JsonHelper _json = new JsonHelper(_param);
                    long _id = Convert.ToInt64(_json.GetVar("ID"));

                    if (_id == 0)
                    {
                        _rm.Success = -2;
                        _rm.ErrorMessage = "未找到配置的程序信息";
                        return _rm;
                    }

                    ServiceInfo _serviceInfo = ConfigBLL.ServiceInfoList.Find(it => it.ID == _id);
                    if (_serviceInfo == null)
                    {
                        _rm.Success = -2;
                        _rm.ErrorMessage = "未找到配置的程序信息";
                        return _rm;
                    }
                    else
                    {
                        if (!WindowsServiceHelper.IsServiceIsExisted(_serviceInfo.ServiceName))
                        {
                            _rm.Success = 0;
                            _rm.ErrorMessage = "服务未安装!";
                            return _rm;
                        }

                        if (!WindowsServiceHelper.IsServiceStart(_serviceInfo.ServiceName))
                        {
                            _rm.Success = 0;
                            _rm.ErrorMessage = "服务未启动!";
                            return _rm;
                        }

                        //关闭服务
                        if (!JLHelper.WindowsServiceHelper.StopService(_serviceInfo.ServiceName))
                        {
                            _rm.Success = 0;
                            _rm.ErrorMessage = "停止服务失败!";
                            return _rm;
                        }

                        //更新文件
                        using (Process p = new Process())
                        {
                            p.StartInfo.FileName = "TortoiseProc.exe"; //可执行程序路径
                            p.StartInfo.Arguments = "/command:update /path:" + FileHelper.GetFileDirectoryName(_serviceInfo.FilePath) + " /closeonend:1";//参数以空格分隔，如果某个参数为空，可以传入""
                            p.StartInfo.UseShellExecute = true;//是否使用操作系统shell启动
                            p.StartInfo.CreateNoWindow = true;//不显示程序窗口
                            p.StartInfo.Verb = "runas";
                            p.Start();
                            p.WaitForExit();
                            //正常运行结束放回代码为0
                            if (p.ExitCode == 0)
                            {
                                _rm.Success = 1;
                                _rm.Result = true;
                            }
                        }


                        //启动服务
                        if (!JLHelper.WindowsServiceHelper.StartService(_serviceInfo.ServiceName))
                        {
                            _rm.Success = 0;
                            _rm.ErrorMessage = "启动服务失败!";
                            return _rm;
                        }

                        _rm.Success = 0;

                    }
                }
            }
            catch (Exception ex)
            {
                string _errorID = Convert.ToString(NetHelperCore.CommonHelper.GetNewID(1));
                LogHelper.WriteLog(LogHelper.LogType.Error, _errorID + "---" + ex.Message + "\r\n" + ex.StackTrace, "", new StackTrace(new StackFrame(true)).GetFrame(0).GetMethod().Name);
                _rm.Success = 0;
                _rm.ErrorMessage = "错误代码:" + _errorID;
            }


            return _rm;
        }

    }
}
